package algorithms;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * Convenience class to write and read gzip files using java.util.zip package.
 * @author Kevin Fehrenbach
 * @author Johannes Mory
 */
public class GZip implements LosslessCompressionAlgorithm
{
	private String _extension = "gzip";

	@Override
	public void encode(File filenameIn, File filenameOut) throws IOException {
		
		FileInputStream fileIn = new FileInputStream(filenameIn);
		GZIPOutputStream gzipFile = new GZIPOutputStream(new FileOutputStream(filenameOut));
		
		int length;
		byte[] buffer = new byte[8192];		
		while((length = fileIn.read(buffer)) != -1)
		{
			gzipFile.write(buffer, 0, length);
		}
		fileIn.close();
		gzipFile.close();
	}
	
	@Override
	public void decode(File fileIn, File fileOut) throws java.io.IOException {

		FileOutputStream gunzipFile = new FileOutputStream(fileOut);
		GZIPInputStream gzipFile = new GZIPInputStream(new FileInputStream(fileIn));
		
		int length;
		byte[] buffer = new byte[8192];
		while((length = gzipFile.read(buffer)) != -1)
		{
			gunzipFile.write(buffer, 0, length);
		}
		gunzipFile.close();
		gzipFile.close();
	}

	@Override
	public String getFileExtension() {
		return _extension;
	}

	@Override
	public void setFileExtension(String name) {
		_extension = name;		
	}	

}
